/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jfrmAdicionarUsuarioComunidade.java
 *
 * Created on 05/11/2011, 11:07:10
 */
package br.ufc.si.poo.orkut.gui;

import br.ufc.si.poo.orkut.beans.comunidade.Comunidade;
import br.ufc.si.poo.orkut.beans.forum.Forum;
import br.ufc.si.poo.orkut.beans.usuario.Usuario;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author italoney
 */
public class jfrmAdicionarUsuarioComunidade extends javax.swing.JFrame {

    //<editor-fold defaultstate="collapsed" desc="Membros privados">
    private Map<String, Comunidade> comunidades;
    private Map<String, Usuario> usuarios;
    private Map<String, Forum> foruns;
    //</editor-fold>    

    /** Creates new form jfrmAdicionarUsuarioComunidade */
    public jfrmAdicionarUsuarioComunidade() {
        initComponents();
    }

    /**
     * @author italoney
     * Contrutor para inicializar propriedades
     * @param comunidades comunidades disponiveis
     * @param usuarios usuários disponiveis
     * @param foruns foruns disponiveis
     */
    public jfrmAdicionarUsuarioComunidade(Map<String, Comunidade> comunidades, Map<String, Usuario> usuarios, Map<String, Forum> foruns) {
        initComponents();
        inicialicarCampos();

        this.comunidades = comunidades;
        this.usuarios = usuarios;
        this.foruns = foruns;

        preencherCombComunidades();
        preencherListaUsuarios();
        preencherListaRelacionamento();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jbSair = new javax.swing.JButton();
        jbSalvar = new javax.swing.JButton();
        jbAdicionar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jlistUsuarios = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlistRelacionamento = new javax.swing.JList();
        jcmbComunidades = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setUndecorated(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Relacionamento Usuario x Comunidade", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Monospaced", 1, 14))); // NOI18N

        jbSair.setText("Sair");
        jbSair.setMaximumSize(new java.awt.Dimension(63, 23));
        jbSair.setMinimumSize(new java.awt.Dimension(63, 23));
        jbSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSairActionPerformed(evt);
            }
        });

        jbSalvar.setText("Salvar");
        jbSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSalvarActionPerformed(evt);
            }
        });

        jbAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/ufc/si/poo/orkut/gui/img/adicionar.png"))); // NOI18N
        jbAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAdicionarActionPerformed(evt);
            }
        });

        jlistUsuarios.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "jlistUsuarios" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jlistUsuarios);

        jlistRelacionamento.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "jlistRelacionamento" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jlistRelacionamento);

        jcmbComunidades.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jbSalvar)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jbAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(50, 50, 50)
                                .addComponent(jbSair, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jcmbComunidades, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jcmbComunidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jbSair, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbSalvar)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(110, 110, 110)
                        .addComponent(jbAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-520)/2, (screenSize.height-364)/2, 520, 364);
    }// </editor-fold>//GEN-END:initComponents

    private void jbAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAdicionarActionPerformed
        Comunidade c = (Comunidade) jcmbComunidades.getSelectedItem();
        Comunidade as = this.comunidades.get(c.getTitulo());


        if (jlistUsuarios.getSelectedValues().length >= 1) {
            for (Object obj : jlistUsuarios.getSelectedValues()) {
                Usuario us = (Usuario) obj;
                if (as.contemUsuario(us)) {
                    JOptionPane.showMessageDialog(null, "O usuario: "
                            + us.getNome() + " já esta na comunidade", "Atenção",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    as.adicionarUsuario(us);
                    this.comunidades.put(as.getTitulo(), as);
                }
            }
            if (jlistUsuarios.getSelectedValues().length > 1) {
                JOptionPane.showMessageDialog(null, "Usuarios adcionados!", "Aviso", 1);
            } else {
                JOptionPane.showMessageDialog(null, "Usuario adcionado!", "Aviso", 1);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Selecione no mínimo um usuario", "Erro",
                    JOptionPane.ERROR_MESSAGE);
        }
        preencherListaRelacionamento();
    }//GEN-LAST:event_jbAdicionarActionPerformed

    private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed
        jfrmPrincipal m = new jfrmPrincipal();
        m.atualizarListas(comunidades, usuarios, foruns);

        this.dispose();
    }//GEN-LAST:event_jbSalvarActionPerformed

    private void jbSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSairActionPerformed
        jfrmPrincipal m = new jfrmPrincipal();
        m.atualizarListas(comunidades, usuarios, foruns);
        this.dispose();
    }//GEN-LAST:event_jbSairActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new jfrmAdicionarUsuarioComunidade().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbAdicionar;
    private javax.swing.JButton jbSair;
    private javax.swing.JButton jbSalvar;
    private javax.swing.JComboBox jcmbComunidades;
    private javax.swing.JList jlistRelacionamento;
    private javax.swing.JList jlistUsuarios;
    // End of variables declaration//GEN-END:variables

    /**
     * @author italoney
     * Preencher lista de relacionamentos de acordo com a comunidade selecionada.
     */
    private void preencherListaRelacionamento() {
        Comunidade comunidade = (Comunidade) jcmbComunidades.getSelectedItem();

        Comunidade as = this.comunidades.get(comunidade.getTitulo());

        DefaultListModel dlm = new DefaultListModel();

//        if (comunidade instanceof ComunidadePrivada) {

        for (Usuario usuario : as.getUsuarios()) {
            dlm.addElement(usuario);
        }

        jlistRelacionamento.setModel(dlm);
//        }

//        if (comunidade instanceof ComunidadePublica) {
//
//            for (Usuario usuario : comunidade.getUsuarios()) {
//                dlm.addElement(usuario);
//            }
//
//            jList1.setModel(dlm);
//        }

    }

    /**
     * @author italoney
     * Preencher combobox com as comunidades disponiveis para relacionamento.
     */
    private void preencherCombComunidades() {
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel();

        for (Comunidade comunidade : this.comunidades.values()) {
            dcbm.addElement(comunidade);
        }

        jcmbComunidades.setModel(dcbm);
    }

    /**
     * @author italoney
     * Preencher lista de usuários disponiveis para relacionamento.
     */
    private void preencherListaUsuarios() {
        DefaultListModel dlm = new DefaultListModel();
        for (Usuario usuario : this.usuarios.values()) {
            dlm.addElement(usuario);
        }

        jlistUsuarios.setModel(dlm);
    }

    /**
     * @author italoney
     * Inicializar campos do focmulário
     */
    private void inicialicarCampos() {
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
        DefaultListModel dlm = new DefaultListModel();
        jcmbComunidades.setModel(dcbm);
        jlistRelacionamento.setModel(dlm);
        jlistUsuarios.setModel(dlm);

    }
}
